from datetime import *
from flask import Blueprint,request,jsonify
import requests
from conf.comm import sqlalchemy_context
from database import *
from werkzeug.security import generate_password_hash,check_password_hash
from utils.comm import send_message
from utils.rediscoon import r
from utils.jwt_token import myjwt
import json
import re
import random
import time
#蓝图初始化
bp_users = Blueprint('users',__name__)
#注册功能实现
@bp_users.route('/reg',methods=['POST','GET'])
@sqlalchemy_context()
def reg():
    if request.method == 'POST':
        data = request.data
        if not data:
            data = request.form
        else:
            
            data = json.loads(request.data)

        
        if not re.match('^1[3-9]\d{9}$', data['mobile']):
            return jsonify({'code':10012})

        try:
            
            username = data['username']
            password = data['password']
            mobile = data['mobile']
            user = User(username=username,password=generate_password_hash(password),mobile=mobile)
            db.session.add(user)
            db.session.commit()
            return jsonify({'code':200})
        except:
            return jsonify({'code':10010})

#发送验证码
@bp_users.route('/login',methods=['POST','GET'])
@sqlalchemy_context()
def login():

    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(request.data)
        else:
            data = request.form
        mobile = data['mobile']
        #判断是否为空
        if not mobile:
            return jsonify({'code':20010,'mes':'必须输入正确的手机号'})
        #判断格式是否正确
        if not re.match('^1[3-9]\d{9}$',mobile):
            return jsonify({'code':20016,'mes':'手机号格式不正确'})
    
          
        codes = r.get_str(mobile)
        if codes:
            return jsonify({'code':20011,'mes':'60秒内不能再发了'})
        
        #生成6位数
        code = random.randint(100000, 999999)
        flag = send_message(mobile, code, 1)
        if flag:
            r.set_str(mobile,60,code)
            return jsonify({'code':200,'codes':code})
        else:
            return jsonify({'code':20012,'mes':'发送失败'})

#用户名密码登录
@bp_users.route('/login1',methods=['POST','GET'])
@sqlalchemy_context()
def login1():
    data=json.loads(request.data)
    username = data['username']
    password = data['password']
    user = User.query.filter_by(username=username).first()
    if user:
        if check_password_hash(user.password,password):
            token = myjwt.encode_jwt({'id':user.id})
            return jsonify({'code':200,'token':token,'userid':user.id,'username':user.username})
        else:
            #密码失败后
            #先根据username判断之前是否已经错误过
            record = Record.query.filter_by(username=username).first()
            #如果没有的话，就往表里添加东西
            if not record:
                record = Record(username=username,count=1)
                db.session.add(record)
                db.session.commit()
            else:
                #如果有的话
                #先获取下当前时间，再获取当时登录错误的时间
                #timestamp 转一下秒，除以3600，变成小时
                time1 = datetime.datetime.now()
                time2 = record.losertime.timestamp()/3600
                
                print(time1,"---",time2)
                #如果 时间大于24，就把次数变成0 再次进行操作
                if time1.timestamp()/3600 - time2 >24:
                    Record.query.filter_by(username=username).update({'count':0,'losertime':time1})
                    db.session.commit()
                
                if record.count <3:
                    Record.query.filter_by(username=username).update({'count':record.count+1})
                    db.session.commit()
                else:
                    return jsonify({'code':20017,'mes':'今日已三次'})

            return jsonify({'code':20014,'mes':'密码错误'})
    else:
        return jsonify({'code':20015,'mes':'用户名错误'})

    


#手机号登录
@bp_users.route('/login2',methods=['POST'])
@sqlalchemy_context()
def login2():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    mobile = data['mobile']
    codes = data['codes']
    code = r.get_str(mobile)
    if re.match('^1[3-9]\d{9}$',mobile):
        if code:
            if str(codes) == (code):
                user = User.query.filter_by(mobile=mobile).first()
                if not user:
                    user = User(username=mobile,mobile=mobile)
                    db.session.add(user)
                    db.session.commit()
                r.del_str(mobile)
                token = myjwt.encode_jwt({'id':user.id})
                return jsonify({'code':200,'userid':user.id,'token':token,'username':user.username})
            else:
                return jsonify({'code':20013,'mes':'验证码不正确'})
        
        else:
            return jsonify({'code':20014,'mes':'验证码发送失败'})
    else:
        return jsonify({'code':20015,'mes':'手机号格式不正确'})
        